﻿using Polly;
using Polly.Timeout;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace Common
{
    public class Wrap : DemoBase
    {
        public override string DemoName => "Polly-Wrap Demo";

        public override void RunDemo()
        {
            //https://github.com/beckjin/PollySamples/blob/master/App/Polly/Wrap.cs
            base.Init();
            int timeout = 2;
            ISyncPolicy policyException = Policy.Handle<TimeoutRejectedException>()
                    .Fallback(() =>
                    {
                        PrintErrorLog("执行降级该执行的操作");
                    });
            ISyncPolicy policyTimeout = Policy.Timeout(timeout, TimeoutStrategy.Pessimistic);
            //ISyncPolicy mainPolicy = Policy.Wrap(policyTimeout, policyException);
            ISyncPolicy mainPolicy = policyTimeout.Wrap(policyException);
            try
            {
                for (int i = 0; i < 5; i++)
                {
                    mainPolicy.Execute(RequestFromWeb);
                }
            }
            catch (Exception e)
            {
                PrintError($"异常：{e.GetType().Name},{e.Message}");
            }
        }

        private void RequestFromWeb()
        {
            if (new Random().Next(10) < 5)
            {
                PrintLog("开始请求大数据包");
                Thread.Sleep(3000);
                PrintSuccessLog("请求大数据包成功");
            }
            else
            {
                PrintLog("开始请求小数据包");
                Thread.Sleep(100);
                PrintSuccessLog("请求小数据包成功");
            }
        }
    }
}
